package javax.core.spring.security.service;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.core.cache.XCacheManager;
import javax.core.security.PrincipalObjectParser;
import java.util.UUID;

@Component
public class SecuritySessionManager {

    @Autowired
    private XCacheManager cacheManager;
    Gson gson = new Gson();
    @Autowired
    private PrincipalObjectParser principalObjectParser;

    public <T> T loadObjectByToken(String tokenKey, Class<T> clazz) {
        T value = cacheManager.getData(tokenKey, clazz);
        if (value != null && value.getClass().equals(clazz)) {
            return clazz.cast(value);
        }
        return null;
    }

    public void savePrincipalObject(String tokenKey, Object principal, long expiredSeconds) {
        cacheManager.setData(tokenKey, principal, expiredSeconds);
    }

    /**
     * 默认是把数据存储为JSON String 到缓存里面
     **/
    public Object loadPrincipalByToken(String tokenKey) {
        String value = cacheManager.getData(tokenKey, String.class);
        if (value != null) {
            return principalObjectParser.parsePrincipalObject(value);
        }
        return null;
    }

    public void savePrincipal(String tokenKey, Object principal, long expiredSeconds) {
        String jsonStr = gson.toJson(principal);
        cacheManager.setData(tokenKey, jsonStr, expiredSeconds);
    }

    /**
     * 保存对象到session并返回一个自动生成的 token
     */
    public String savePrincipal(Object principal, long expiredSeconds) {
        String jsonStr = gson.toJson(principal);
        String tokenKey = UUID.randomUUID().toString();
        cacheManager.setData(tokenKey, jsonStr, expiredSeconds);
        return tokenKey;
    }
}
